<?php
// +----------------------------------------------------------------------
// | B5Yii2CMF V3.0 [快捷通用基础管理开发平台]
// +----------------------------------------------------------------------
// | Author: 冰舞 <357145480@qq.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace common\actions;

use common\extend\exception\ErrorCode;
use common\helpers\Result;
use common\helpers\UploadHelper;
use yii\base\Action;
use Yii;

class UploadAction extends Action
{
    public string $type = 'img';
    public string $cat = '';
    public array $ext = [];
    public int $maxSize = 0;
    public int $width = 0;
    public int $height = 0;
    public bool $water = false;
    public int $success = ErrorCode::COMMON_SUCCESS;
    public int $error = ErrorCode::COMMON_ERROR;

    public function run(): array
    {
        $method = $this->type . 'Upload';
        if (!method_exists($this, $method)) {
            $result = Result::fail('上传类型错误');
        } else {
            $result = $this->$method();
        }
        $isOk = $result['success'] ?? false;
        if ($isOk) {
            return Result::success($result['msg'] ?? '操作成功', $result['data'] ?? [], [], $this->success);
        } else {
            return Result::error($result['msg'] ?? '操作失败', $this->error, $result['data'] ?? []);
        }
    }

    /**
     * 图片上传
     * @return array
     */
    private function imgUpload(): array
    {
        if ($this->width <= 0 && $this->height <= 0) {
            $this->width = intval(Yii::$app->request->post('width', 0));
            $this->height = intval(Yii::$app->request->post('height', 0));
        }
        $upload = new UploadHelper();
        return $upload->setCat($this->cat ?: Yii::$app->request->post('cat', ''))
            ->setWater($this->water)
            ->setExt($this->ext)
            ->setWidth($this->width)
            ->setHeight($this->height)
            ->setMaxSize($this->maxSize)->run();
    }

    /**
     * 文件上传
     * @return array
     */
    private function fileUpload(): array
    {
        $upload = new UploadHelper();
        return $upload->setCat($this->cat ?: Yii::$app->request->post('cat', ''))
            ->setType('file')->run();
    }

    /**
     * 视频上传
     * @return array
     */
    private function videoUpload(): array
    {
        $upload = new UploadHelper();
        return $upload->setCat($this->cat ?: Yii::$app->request->post('cat', ''))
            ->setType('video')->run();
    }
}